package com.fom2008;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Contacts;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.fom2008.db.FomTag;

public class FOM2008 extends Activity {

	private static final int	PICK_PHOTO_RESULT	= 1;
	private static final int	PICK_CONTACT_RESULT	= 2;
	private static final String	TAG					= "FOM";

	// View objects
	private Button				getPhoto;
	private Button				getContact;
	private Button				createContact;

	private Handler				messageHandler;
	private Button				locate;

	private FomObserver			observer;
	private Button	gears;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Set the content view from the XML layout
		setContentView(R.layout.main);

		// this is used by the Observer
		messageHandler = new Handler();
		// This is the observer
		observer = new FomObserver(messageHandler);

		// Get the button from the XML layout.
		getPhoto = (Button) findViewById(R.id.getPhoto);

		// Add a click listener to the button press
		getPhoto.setOnClickListener(new View.OnClickListener() {
			// The event that is fired when we click the button
			public void onClick(View v) {
				// Select the photo from a list of photo. This listing is not
				// handle by our application. The system will start the correct
				// intent for the selection. If there are several, the system
				// will choose the one defined as default. If none, it will give
				// a list for the user to choose from. If no activity answers
				// the intent, then we should get an error

				// Our intention is to pick an image
				Intent intent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI);

				// We start the activity (external to this app) and wait for the
				// result
				startActivityForResult(intent, PICK_PHOTO_RESULT);
			}
		});

		getContact = (Button) findViewById(R.id.getContact);

		// This is similar to the above but from a list of contacts
		getContact.setOnClickListener(new View.OnClickListener() {
			// The event that is fired when we click the button
			public void onClick(View v) {

				// Our intention is to pick a contact
				Intent intent = new Intent(Intent.ACTION_PICK, Contacts.People.CONTENT_URI);

				// We start the activity (external to this app) and wait for the
				// result
				startActivityForResult(intent, PICK_CONTACT_RESULT);
			}
		});

		createContact = (Button) findViewById(R.id.createContact);
		createContact.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Inserting a new contact. The system will choose which
				// activity suits this action best
				Intent intent = new Intent(Intent.ACTION_INSERT, Contacts.People.CONTENT_URI);
				startActivityForResult(intent, PICK_CONTACT_RESULT);
			}
		});

		locate = (Button) findViewById(R.id.locate);
		locate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Instead of creating our MapView and handle the positioning,
				// we use the map application. The map application will answer
				// any call to a URI that begins with "geo:"
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=Hilton+London+Olympia+Hotel"));
				startActivity(intent);
			}
		});
		
		gears = (Button) findViewById(R.id.gear);
		gears.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// This should launch the browser and test the geoLocation API of gears. Does not seem to work with the emulator.
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://code.google.com/apis/gears/samples/hello_world_geolocation.html"));
				startActivity(intent);
			}
		});
	}

	@Override
	protected void onStart() {
		super.onStart();

		// We observe anything that happens against the URI for the contacts...
		// In the content provider, we use the notifyChange to notify any
		// observer.
		getContentResolver().registerContentObserver(Contacts.People.CONTENT_URI, true, observer);
	}

	@Override
	protected void onStop() {
		super.onStop();

		// Ensure that you unregister the observer when your application goes
		// down
		getContentResolver().unregisterContentObserver(observer);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		// Something went wrong
		if (resultCode == RESULT_CANCELED) {
			Toast.makeText(this, "You did not select anything!", 1000).show();
		} else if (resultCode == RESULT_OK) {
			ContentValues values = new ContentValues();
			switch (requestCode) {
				case PICK_PHOTO_RESULT:
					values.put(FomTag.Tags.DESCRIPTION, "A photo");
					values.put(FomTag.Tags.TAGGED_CONTENT, data.getDataString());
					break;
				case PICK_CONTACT_RESULT:
					values.put(FomTag.Tags.DESCRIPTION, "A Contact");
					values.put(FomTag.Tags.TAGGED_CONTENT, data.getDataString());
					break;
				default:
					Log.e(TAG, "The requested code is " + requestCode + " and its code " + resultCode + " for data: " + data);
					break;
			}

			// If we are here, everything should be fine.
			values.putAll(getLocation());

			// Finally we save the values into the DB
			Uri uri = getContentResolver().insert(FomTag.Tags.CONTENT_URI, values);

			// We create a new intent from the newly created data
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);

			// We start the new intent as activity
			startActivity(intent);
		}
	}

	// Method which captures the current location of the phone
	private ContentValues getLocation() {
		ContentValues val = new ContentValues();

		// First we need a location manager given by the system. Ensure you have
		// the permission to access the location manager - this is set in the
		// manifest file
		LocationManager locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		// The location manager manages a list of location provider. In our case
		// we will use the GPS. the getLastknownLocation gives us the latest
		// location found. This can be seen as cache but might not be accurate.
		// Ensure you use the Google map with the mock up data in order to
		// update the location.
		Location loc = locMan.getLastKnownLocation("gps");

		if (loc != null) {
			// The location should give use the latitude and longitude
			val.put(FomTag.Tags.LATITUDE, loc.getLatitude());
			val.put(FomTag.Tags.LONGITUDE, loc.getLongitude());
		} else {
			Toast.makeText(this, "Could not read location, have you setup the location mockup?", 5000).show();
			val.put(FomTag.Tags.LATITUDE, 0);
			val.put(FomTag.Tags.LONGITUDE, 0);
		}
		return val;
	}

	// Creates the menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		// Add the different menus
		menu.add(0, Menu.FIRST, 0, "View all on map");
		menu.add(0, Menu.FIRST + 1, 0, "View all as list");
		return true;
	}

	// Handles the selection against the menu
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case Menu.FIRST:
				Intent intent = new Intent(Intent.ACTION_VIEW, FomTag.Tags.CONTENT_URI);
				startActivity(intent);
				return true;
			case Menu.FIRST + 1:
				// Starting an activity directly without letting the system
				// choose which activity is best
				Intent intent2 = new Intent(this, FomTagListView.class);
				startActivity(intent2);
				return true;
		}
		return false;
	}

}